<template>
  <div class="form-wrapper">
    <div class="block-header">
      <n-space align="center">
        <n-button @click="handleBack" secondary circle size="small">
          <template #icon>
            <n-icon>
              <ChevronBackOutline></ChevronBackOutline>
            </n-icon>
          </template>
        </n-button>
        <div class="title">{{ formStore.formInfo.name }}详情:</div>
        <n-button
          @click="goEditDetail"
          size="small"
          type="primary"
          secondary
          strong
          >{{ $t("edit form") }}</n-button
        >
        <!-- <n-select
          size="small"
          style="width: 180px"
          :options="sortOptions"
          v-model:value="searchParams.sort"
        ></n-select> -->
      </n-space>
      <n-space style="margin-left: auto">
        <!-- <n-input
          style="width: 150px"
          size="small"
          :placeholder="$t('please input keyword')"
        >
          <template #prefix>
            <n-icon :component="SearchOutline" />
          </template>
        </n-input>
        <n-button size="small" type="primary" secondary strong>{{
          $t("new form")
        }}</n-button> -->
      </n-space>
    </div>
    <div class="card">
      <n-space align="center">
        <div class="title">总览</div>
        <n-button
          @click="handleExport"
          size="small"
          type="primary"
          secondary
          stronger
          >导出数据</n-button
        >
        <n-button
          @click="handleImport"
          size="small"
          type="error"
          secondary
          stronger
          >导入数据</n-button
        >
        <n-button size="small" type="info" secondary stronger @click="staFun">
          统计</n-button
        >
      </n-space>
      <div class="summary">
        <div>
          <n-progress
            :color="themeVars.successColor"
            size="small"
            type="circle"
            :percentage="
              statisticsData.total == 0
                ? 0
                : (
                    (statisticsData.complete / statisticsData.total) *
                    100
                  ).toFixed(0)
            "
          />
          <div class="summary-title">
            已完成:{{ statisticsData.complete }}/{{ statisticsData.total }}
          </div>
        </div>
      </div>
      <div class="chart-list"></div>
    </div>
    <div class="share-list card">
      <n-space class="user-list" align="center">
        <!-- <div
          :class="['user-item', selectUserIndex == index ? 'active' : '']"
          v-for="(item, index) in formStore.formInfo.joinUsers"
          @click="handleUserSelect(index)"
        >
          <n-avatar :src="item.headImg" round></n-avatar>
          <span class="user-name">{{ item.name }}</span>
        </div> -->
        <n-badge
          v-for="(item, index) in formStore.formInfo.joinUsers"
          :type="
            statusMap[
              statisticsData['statusList']?.find(
                (subItem) => subItem.label == item.name
              )?.value || 0
            ]?.type
          "
          :value="
            statusMap[
              statisticsData['statusList']?.find(
                (subItem) => subItem.label == item.name
              )?.value || 0
            ]?.label
          "
          :offset="[-15, 0]"
        >
          <n-tag
            class="user-item"
            strong
            checkable
            :checked="selectUserIndex == index"
            @click="handleUserSelect(index)"
          >
            <template #avatar>
              <n-avatar :src="item.headImg" round></n-avatar>
            </template>

            <span class="user-name">{{ item.name }}</span></n-tag
          >
        </n-badge>

        <n-button @click="handleInvite" class="add-user" type="primary" dashed>
          邀请用户
        </n-button>
      </n-space>
      <n-divider></n-divider>
      <div v-if="selectUserIndex != -1" class="user-detail">
        <div class="user-form">
          <div class="left">
            <n-scrollbar
              v-if="formStore.submitInfo"
              style="height: calc(100vh - 300px)"
            >
              <!-- <formBuilder
                ref="formBuilderRef"
                :schema="(schema as any)"
              ></formBuilder> -->
              <div
                :class="[
                  'component-item',
                  formStore.selectComponent() &&
                  formStore.selectComponent()['prop'] == item.prop
                    ? 'active'
                    : '',
                ]"
                :key="item.prop"
                v-for="(item, index) in formStore.formInfo.content"
              >
                <n-form-item
                  :required="item.required == 1"
                  :label="item.name || item.prop"
                  style="flex: 1"
                >
                  <component :is="renderComp(index, item.type)"></component>
                </n-form-item>
                <div class="verify">
                  <div class="title">审核</div>
                  <div class="content" v-if="formStore.submitInfo[item.prop]">
                    <n-input-number
                      v-if="formStore.submitInfo[item.prop]"
                      placeholder="请输入分数"
                      button-placement="both"
                      style="
                        width: 160px;
                        margin-bottom: 12px;
                        text-align: center;
                      "
                      v-model:value="
                        formStore.submitInfo[item.prop].verifyScore
                      "
                      ><template #suffix> 分 </template></n-input-number
                    >
                    <n-input
                      placeholder="请输入审核内容"
                      type="textarea"
                      v-model:value="formStore.submitInfo[item.prop].verifyText"
                    ></n-input>
                  </div>
                </div>
                <n-divider style="margin: 12px 0 !important"></n-divider>
              </div>
            </n-scrollbar>
            <div style="height: calc(100vh - 300px)" v-else>
              <n-result status="info" title="等待用户填写" description="">
                <template #footer>
                  <n-button @click="handleNotify">通知用户填写</n-button>
                </template>
              </n-result>
            </div>
          </div>

          <div v-if="formStore.submitInfo" class="right">
            <div class="title">
              {{
                formStore.formInfo.joinUsers[selectUserIndex]?.name
              }}提交的详情:
            </div>
            <div class="row-list">
              <div class="row">
                <div class="title">提交日期：</div>
                <div class="value">{{ selectRecord["updateTime"] }}</div>
              </div>
              <div class="row">
                <div class="title">状态：</div>
                <div class="value">
                  <n-select
                    @update:value="handleUpdateRecord"
                    style="width: 120px"
                    size="small"
                    :options="statusMap"
                    v-model:value="selectRecord['status']"
                  ></n-select>
                </div>
              </div>
            </div>
            <div class="title" style="margin-top: 24px">操作:</div>
            <n-space style="margin-top: 12px; width: 230px">
              <n-button
                @click="handlePatchRecord"
                type="primary"
                secondary
                stonger
                size="small"
                >修改审核信息</n-button
              >
              <n-button
                @click="handleNotify"
                type="info"
                secondary
                stonger
                size="small"
                >提醒</n-button
              >
              <n-button
                @click="handleClear"
                type="error"
                secondary
                stonger
                size="small"
                >清空记录</n-button
              >
              <n-button type="warning" secondary stonger size="small"
                >强制修改</n-button
              >
              <n-button type="info" secondary stonger size="small"
                >下载</n-button
              >
            </n-space>
          </div>
        </div>
      </div>
    </div>
    <n-modal v-model:show="showAddUser">
      <n-card
        style="width: 600px"
        title="邀请用户"
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
      >
        <!-- <template #header-extra> 噢！ </template> -->
        <n-transfer
          ref="transfer"
          v-model:value="userIndexList"
          :options="totalUsers"
          :render-target-label="renderLabel"
        />
        <template #footer>
          <n-space justify="end">
            <n-button
              @click="handleUserSubmit"
              type="primary"
              secondary
              stronger
              >提交</n-button
            >
          </n-space>
        </template>
      </n-card>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed, h } from "vue";
import {
  SearchOutline,
  EllipsisVerticalOutline,
  DocumentTextOutline,
  ChevronBackOutline,
} from "@vicons/ionicons5";
import {
  addFormApi,
  deleteFormApi,
  getForms,
  joinUsers,
  getFormStatistics,
  getRecordForm,
  getRecordFormByPerson,
  updateRecordForm,
  deleteRecord,
  updateFormApi,
  getFormData,
} from "@/api/form";
import { useRouter, useRoute } from "vue-router";
// import formForm from "./form/addform.vue";
import DialogForm from "@/components/form-builder/dialog.vue";
import addformJson from "./form/add-form.json";
import { useI18n } from "vue-i18n";
import { downloadObjectAsJson, formatPast, importJson } from "@/utils";
import { useMessage, useDialog, useThemeVars, NAvatar } from "naive-ui";
import { v1 } from "uuid";
import { useFormStore } from "@/store/form";
import { getFormUsers } from "@/api/user";
import { useUserStore } from "@/store/user";
import table2excel from "js-table2excel";
import dayjs from "dayjs";
const excelData = ref(); // 用户答题信息数据
const columExcel: any = ref([
  // excel字段表
  {
    title: "id",
    key: "id",
    type: "text",
  },
  {
    title: "题目类型",
    key: "name",
    type: "text",
  },
  {
    title: "题目名称",
    key: "questionName",
    type: "text",
  },
]);
import { statusMap } from "@/struct";
import { addMessage } from "@/api/message";
const userStore = useUserStore();
const components = import.meta.glob(
  "@/pages/form-editor/components/**/index.vue",
  {
    eager: true,
  }
);
const selectRecord = ref({});
const formStore = useFormStore();
const message = useMessage();
const dialog = useDialog();
const { t } = useI18n();
const formFormRef = ref();
const router = useRouter();
const route = useRoute();
const selectUserIndex = ref(-1);
const themeVars = useThemeVars();
const showAddUser = ref(false);

const statisticsData = ref({ complete: 0, total: 10 });
const schema = computed(() => {
  return {
    title: "新建图层",
    size: "medium",
    labelWidth: "auto",
    labelPlacement: "top",
    columns: formStore.formInfo.content,
  };
});

const userIndexList = computed({
  get() {
    return formStore.formInfo.joinUsers.map((item) => item.id);
  },
  set(val) {
    console.log(val);
    formStore.formInfo.joinUsers = val.map((item) => {
      return totalUsers.value.find((subItem) => subItem.value == item);
    });
  },
});
const totalUsers = ref([]);
const renderLabel = ({ option }) => {
  console.log(option);
  return h(
    "div",
    {
      style: {
        display: "flex",
        margin: "6px 0",
      },
    },
    {
      default: () => [
        h(NAvatar, {
          round: true,
          src: option.headImg as string,
          size: "small",
          fallbackSrc: option.headImg,
        }),
        h(
          "div",
          {
            style: {
              display: "flex",
              marginLeft: "6px",
              alignSelf: "center",
            },
          },
          { default: () => option.label }
        ),
      ],
    }
  );
};
const goEditDetail = () => {
  const id = route.query.id;
  // router;
  // window.location.replace();
  window.open(`/editor/#/form-editor?id=${id}`, "_blank");
};
const handleUserSelect = (index: number) => {
  selectUserIndex.value = index;
  formStore.submitInfo = null;
  getRecordFormByPerson({
    pid: route.query.id as string,
    userId: userIndexList.value[index],
  })
    .then((res) => {
      if (res) {
        formStore.submitInfo = res.content;
        selectRecord.value = res;
      } else {
        selectRecord.value = {};
      }

      console.log(res);
    })
    .catch((e) => {
      console.log(e);
    });
  // getRecordForm();
};
const renderComp = (index: number, type: string) => {
  // console.log(`../form-editor/components/${type}/index.vue`);
  // console.log(`/src/pages/form-editor/components/${type}/index.vue`);
  return h(
    components[`/src/pages/form-editor/components/${type}/index.vue`][
      "default"
    ],
    {
      readonly: true,
      debug: false,
      prop: formStore.formInfo.content[index].prop,
      ...formStore.formInfo.content[index].props,
      value: formStore.formInfo.content[index].default,
      onUpdateValue: (val) => (formStore.formInfo.content[index].default = val),
    }
  );
};
const handleBack = () => {
  router.back();
};
const handleUserSubmit = () => {
  console.log(formStore.formInfo.joinUsers);
  showAddUser.value = false;
  joinUsers({ pid: route.query.id, users: userIndexList.value })
    .then((res) => {
      message.success("更新用户成功");
    })
    .catch((e) => {
      message.error("更新用户失败");
    });
};
const handleInvite = () => {
  getFormUsers({
    page: 1,
    size: 100,
    departmentIds: [userStore.userInfo.departmentId],
    sort: "desc",
    order: "createTime",
  }).then((res: any) => {
    console.log(res);
    totalUsers.value = res.data.list
      .filter((item) => item.roleName == "填报员")
      .map((item) => {
        return {
          id: item.id,
          value: item.id,
          headImg: item.headImg,
          label: item.name,
          name: item.name,
        };
      });
    showAddUser.value = true;
  });
};
// const sendMessage = (data) => {

// };
const handleUpdateRecord = () => {
  setTimeout(() => {
    updateRecordForm(selectRecord.value)
      .then((res) => {
        message.success(`更新成功`);
      })
      .catch((e) => {
        message.error(`更新失败:${e}`);
      });
  });
};
const handlePatchRecord = () => {
  console.log(selectRecord.value);
  updateRecordForm(selectRecord.value)
    .then((res) => {
      message.success(`修改审核信息成功`);
    })
    .catch((e) => {
      message.error(`修改审核信息失败:${e}`);
    });
};
const handleClear = () => {
  dialog.error({
    title: "清空记录",
    content: "此操作会清空用户当前的填写记录，请确认",
    positiveText: "清空",
    onPositiveClick(e) {
      deleteRecord({ ids: [selectRecord.value["id"]] })
        .then((res) => {
          message.success("清空成功");
          getStatistics();
        })
        .catch((e) => {
          message.error(`清空失败:${e}`);
        });
    },
  });
};
const handleExport = () => {
  console.log(formStore.formInfo);
  downloadObjectAsJson(formStore.formInfo.content, formStore.formInfo.name);
};
const handleImport = () => {
  importJson().then((res: any) => {
    dialog.error({
      title: "导入数据",
      content: "新导入数据将会覆盖原数据，请确认",
      positiveText: "确认覆盖",
      negativeText: "取消",
      onPositiveClick() {
        console.log(res);
        formStore.formInfo.content = res;
        const data = JSON.parse(JSON.stringify(formStore.formInfo));
        delete data.joinUsers;
        updateFormApi(data)
          .then((res) => {
            message.success("导入成功");
          })
          .catch((e) => {
            message.error(`导入失败:${e}`);
          });
      },
    });
  });
};
const handleNotify = () => {
  console.log(formStore.formInfo.joinUsers[selectUserIndex.value]);
  const data = {
    toUser: formStore.formInfo.joinUsers[selectUserIndex.value].id,
    content: "您有新问卷待填写,请立即填写",
    url: `/form-preview?id=${route.query.id}`,
  };
  addMessage(data)
    .then((res) => {
      message.success("通知成功");
    })
    .catch((e) => {
      message.error(`通知失败:${e}`);
    });
};
const getStatistics = () => {
  const id = route.query.id as string;
  formStore.pid = id;
  getFormStatistics({ pid: id }).then((res: any) => {
    formStore.formInfo = res.form;
    delete res.form;
    statisticsData.value = res;
    selectUserIndex.value = -1;
  });
};

/**
 * @author S 获取用户选择数据的信息
 */
const getUserData = async () => {
  const id = route.query.id as string;
  excelData.value = await getFormData({ pid: id });
  // console.log("data", excelData.value);
};

/**
 * @author S 点击导出execl
 */
const staFun = () => {
  const Data = ref([]); // 第一次转换的数据
  const afterData = ref([]); // 第二次转换的数据
  const ThreeData = ref([]); // 第三次转换数据
  const optionsData = ref([]); // options映射表
  const map = new Map(); // 哈希表
  // getUserData()

  // 获取当前时间，用来给excel文件当文件名
  const time = dayjs().format("YYYY-MM-DD HH:mm:ss");

  // 获得所有的options转为数组,格式{label,value},第一次处理
  formStore.formInfo.content.forEach((item) => {
    Data.value.push({
      prop: item.prop,
      name: item.name,
      questionName: item.props.questionName,
    });
    item.props.options.forEach((val) => {
      // optionsData.value.push(val);
      map.set(val.value, val.label);
    });
  });

  // 动态设置eccel表头
  excelData.value.forEach((item) => {
    columExcel.value.push({
      title: item.user.nickName,
      key: item.user.nickName,
      type: "text",
    });

    for (let key in item.content) {
      afterData.value.push({
        prop: key,
        nickName: item.user.nickName,
        ...item.content[key],
      });
    }
  });

  // key,value对应，用来处理答案
  afterData.value.forEach((val1) => {
    if (typeof val1.select == "object") {
      const arr = [];
      if (val1.select instanceof Array) {
        val1.select.forEach((val2) => {
          arr.push(map.get(val2));
        });
      } else {
        for (let key in val1.select) {
          // arr.push(map.get(key));
          arr.push(val1.select[key]);
        }
      }
      val1.anawer = arr.join(",");
    } else {
      val1.anawer = map.get(val1.select);
    }
  });

  // 第三次处理最后push进入数组
  afterData.value.forEach((val1, index) => {
    Data.value.forEach((val2) => {
      if (val1.prop == val2.prop) {
        const urlValue = ref("");
        if (val1.files.length != 0) {
          urlValue.value = val1.files[0].url;
        }
        ThreeData.value.push({
          id: index + 1,
          prop: val1.prop,
          name: val2.name,
          questionName: val2.questionName,
          anawer: val1.anawer,
          files: urlValue.value,
          [val1.nickName]: val1.anawer,
        });
      }
    });
  });

  const fiveData = ref();

  // 最后合并
  const mergedArray = Object.values(
    ThreeData.value.reduce((result, obj) => {
      const { prop, ...rest } = obj;
      if (prop in result) {
        result[prop] = { ...result[prop], ...rest };
      } else {
        result[prop] = { ...rest };
      }
      return result;
    }, {})
  );

  fiveData.value = mergedArray;

  table2excel(columExcel.value, fiveData.value, time);
};

onMounted(() => {
  // formStore.getForm();
  getStatistics();

  getUserData();
});
</script>

<style lang="scss" scoped>
.form-wrapper {
  padding-left: 2px;
}

.block-header {
  display: flex;
  align-items: center;

  .title {
    font-weight: bold;
    font-size: 24px;
  }
}

.card {
  padding: 24px;
  background-color: #fff;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  margin: 12px 0;

  .title {
    font-weight: bold;
    font-size: 16px;
  }
}

.dark .card {
  background-color: #222;
}

.summary {
  display: flex;
  margin: 24px 0;

  .summary-title {
    margin: 12px 0;
    font-weight: bold;
  }
}

.share-list {
  text-align: start;

  .title {
    font-weight: bold;
  }

  .user-list {
    margin: 0;

    .user-item {
      height: 40px;

      .user-name {
        margin-left: 6px;
      }
    }

    .add-user {
      height: 38px;
    }

    .active {
      background-color: #333;
      border: 1px solid #63e2b7;
    }
  }

  .user-detail {
    .user-form {
      display: flex;

      .left {
        flex: 1;
        margin: 12px 0;
      }

      .right {
        margin-left: 24px;
        margin-top: 12px;

        .row {
          margin: 12px 0;
          display: flex;
        }
      }
    }
  }
}

.form-content {
  display: flex;
  margin: 24px 0;
  flex-wrap: wrap;

  .form-item {
    width: 240px;
    height: 140px;
    box-sizing: border-box;
    text-align: left;
    // background-color: rgb(28, 28, 31);
    background-color: #f2f3f5;
    border-radius: 4px;
    padding: 12px;
    margin-right: 24px;
    margin-bottom: 24px;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    flex-direction: column;
    user-select: none;

    .form-header {
      display: flex;
      justify-content: space-between;
    }

    .form-bottom {
      margin-top: auto;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .img {
      width: 44px;
      height: 44px;
      border-radius: 4px;
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: center;
      box-sizing: border-box;
      padding-bottom: 12px;
    }

    .desc {
      font-size: 12px;
      color: grey;
    }
  }

  .add {
    border: 1px dashed #63e2b7;
    background-color: #63e2b711;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .add:hover {
    background-color: #63e2b733 !important;
  }

  .form-item:hover {
    box-shadow: 0px 0px 0px 2px #63e2b799;
    // background-color: rgba(51, 51, 53, 0.8);
    // box-shadow: 0px 0px 10px rgba(255, 255, 255, 0.1);
  }

  .form-item:active {
    // background-color: #63e2b711;
    // box-shadow: 0px 0px 10px rgba(255, 255, 255, 0.1);
  }
}

.dark .form-item {
  background-color: rgb(28, 28, 31) !important;
}
</style>
